博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django不用在数据库中创建新的user表而使用它的后台管理功能
阅读量:2432 次
发布时间:2019-05-10

本文共 6015 字,大约阅读时间需要 20 分钟。

在一个项目中经常要对远端的一个数据库中的数据做修改,每次都写sql感觉很麻烦,就想到能不能直接利用django的后台管理功能呢,当然是可以的,但是要登录django的后台使用它的管理功能必须在对应的数据库创建django后台管理需要的user和Log相关的表,而这个又是不可能的,那能不能不创建user表而仅仅是使用它的后台管理功能呢,答案是可以的

django后台登录需要输入用户名、密码,用户登录验证的backend默认是django.contrib.auth.backends,而它采用的是数据库表的验证,为了不创建新表,我们需要修改登录验证的backends,

修改的方法很简单,在setting.py中添加配置

AUTHENTICATION_BACKENDS = ["houtai.extend.auth.backends.SimpleBackend"]#用户验证的Backend
然后要实现SimpleBackend,验证后需要返回一个User对象,所以还需要实现一个SingleUser类

from __future__ import unicode_literalsfrom houtai.extend.auth.user import SingleUserclass SimpleBackend(object):    """    Authenticates against settings.AUTH_USER_MODEL.    """    def authenticate(self, username=None, password=None):        cur_user = SingleUser()        if cur_user.validate(username,password):            return cur_user            def get_user(self, user_id):        return SingleUser()
from houtai.extend.common import Singletonclass SingleUser(Singleton):    username = "admin"    password = "111111"    is_active = 1    is_staff =1    is_superuser =1    pk = '123456'           def validate(self,username,password):        if username and password:            if username == self.username and password == self.password:                return True        return False    def save(self,update_fields=['last_login']):        return    def has_module_perms(self, app_label):        """        Returns True if the user has any permissions in the given app label.        Uses pretty much the same logic as has_perm, above.        """        # Active superusers have all permissions.        if self.is_active and self.is_superuser:            return True        return False    def has_perm(self, perm, obj=None):        return True
有了上面的backends就能够用admin:111111登录到后台,单很快就会出现下面这个错误:

"Table 'test.django_content_type' doesn't exist"
这时候需要做下面三件事才能搞定:

1、修改admin后台首页的模板:

在url.py中添加admin.site.index_template = 'houtai/index.html'

index.html

{% extends "admin/base_site.html" %}{% load i18n admin_static %}{% block extrastyle %}{
{ block.super }}
{% endblock %}{% block coltype %}colMS{% endblock %}{% block bodyclass %}dashboard{% endblock %}{% block breadcrumbs %}{% endblock %}{% block content %}
{% if app_list %} {% for app in app_list %}
{% for model in app.models %}
{% if model.admin_url %}
{% else %}
{% endif %} {% if model.add_url %}
{% else %}
{% endif %} {% if model.admin_url %}
{% else %}
{% endif %}
{% endfor %}
{% blocktrans with name=app.name %}{
{ name }}{% endblocktrans %}
{ { model.name }} { { model.name }} {% trans 'Add' %}   {% trans 'Change' %}  
{% endfor %}{% else %}

{% trans "You don't have permission to edit anything." %}

{% endif %}
{% endblock %}
2、修改django.contrib.admin.options.py

修改:

action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')
为:

if settings.LOGGING != None:            action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')
修改:

from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )
修改:

from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )
修改:

from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )
3、在setting.py中设置Loging为None
LOGGING  = None#关闭后台日志记录功能
至此就可以用admin:111111登录后台管理远程的数据库了

转载地址:http://nwsmb.baihongyu.com/

你可能感兴趣的文章
mysql 模块使用
查看>>
解决android中Layout文件下的xml文件配好后,R类中不能自动生成相应代码
查看>>
[iOS] photoKit获取所有照片
查看>>
下载安装webstrom及激活
查看>>
Android Studio 之 NDK篇
查看>>
【ASP】简单Url编码和Url解码实例
查看>>
怎样基于谷歌地图的Server缓存公布Image Service服务
查看>>
完美攻略心得之圣魔大战3(Castle Fantisia)艾伦希亚战记(艾伦西亚战记)包含重做版(即新艾伦希亚战记)...
查看>>
浅谈UML的概念和模型之UML九种图
查看>>
BW:BW增量更新方法(假增量)
查看>>
SQLite—homework
查看>>
理解js中的原型链,prototype与__proto__的关系
查看>>
design.js
查看>>
ReactiveCocoa入门教程——第一部分
查看>>
自定义能够for each的类,C#,Java,C++,C++/cli的实现方法
查看>>
Content-Disposition 响应头,设置文件在浏览器打开还是下载
查看>>
oracle 事务测试
查看>>
CSS3动画@keyframes中translate和scale混用出错问题
查看>>
BZOJ 1016--[JSOI2008]最小生成树计数(kruskal&搜索)
查看>>
shell复习笔记----命令与参数
查看>>